package breeze.pixel.weather.moretool.panelmode.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.style.StrikethroughSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextClock;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import breeze.pixel.weather.R;
import breeze.pixel.weather.adapter.AppWeatherManager;
import breeze.pixel.weather.adapter.IAppWeatherHelper;
import breeze.pixel.weather.adapter.weather.WeatherNowAdapter;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.MDialog;
import breeze.pixel.weather.apps_util.utils.MToast;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;
import breeze.pixel.weather.apps_util.views.mtextview.MTextView;
import breeze.pixel.weather.moretool.panelmode.PannelAddTaskActivity;
import breeze.pixel.weather.moretool.panelmode.model.PanelTaskUtil;

public class PanelModeView extends AppCompatActivity implements IPanelModeView {

    private MTextView CityName, Tem, Weather_Text, Wet, WindSpeed, Update;
    private MTextView DefaultText, Voice_text, Date, Week, DefaultText2, DefaultText3, DefaultText4, DefaultText5, DefaultText6, ChangeBackground;
    private SeekBar ChangeVoice;
    private AppSettings sets;
    private ImageView Weather_Icon;
    private MyBatteryListener listener;
    private MTextView battery_name_tv, battery_value_tv;
    private ProgressBar battery;
    private LinearLayout Background, Tasks;
    private View view_line, view_line2, view_line3, view_line4, view_line5;
    private TextClock Clock;
    private Timer time;
    private long updateTime = 0;
    private List<PanelTaskUtil> tasks = new ArrayList<>();
    private static final int _REQUEST_GET_PIC = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_panel_mode);
        init();
        update();
        setStyle(sets.getPanelTheme(), 13);
        //开启定时
        startTimerTask();
        //自动保存
        autoSave();
        //检测缓存
        checkCache();
        //获取电量
        IntentFilter fileter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        listener = new MyBatteryListener();
        registerReceiver(listener, fileter);
    }

    public void init() {
        sets = AppSettings.getInstance(this);
        CityName = findViewById(R.id.panel_style_cityname);
        Background = findViewById(R.id.panel_style_background);
        Clock = findViewById(R.id.panel_style_clock);
        view_line = findViewById(R.id.panel_style_view);
        Tem = findViewById(R.id.panel_style_tem);
        view_line2 = findViewById(R.id.panel_style_view2);
        view_line4 = findViewById(R.id.panel_style_view4);
        view_line3 = findViewById(R.id.panel_style_view3);
        Wet = findViewById(R.id.panel_style_wet);
        Date = findViewById(R.id.panel_style_date);
        Week = findViewById(R.id.panel_style_week);
        WindSpeed = findViewById(R.id.panel_style_windspeed);
        Weather_Text = findViewById(R.id.panel_style_weather_text);
        Weather_Icon = findViewById(R.id.panel_weather_icon);
        Update = findViewById(R.id.panel_style_cloud);
        ChangeVoice = findViewById(R.id.panel_change_voice);
        Tasks = findViewById(R.id.panel_style_tasks);
        battery_value_tv = findViewById(R.id.panel_battery_value_tv);
        battery_name_tv = findViewById(R.id.panel_battery_name_tv);
        battery = findViewById(R.id.panel_battery_progress);
        Voice_text = findViewById(R.id.panel_style_voice_text);
        DefaultText = findViewById(R.id.panel_style_default_text);
        DefaultText2 = findViewById(R.id.panel_style_default_text2);
        DefaultText3 = findViewById(R.id.panel_style_default_text3);
        DefaultText4 = findViewById(R.id.panel_style_default_text4);
        DefaultText5 = findViewById(R.id.panel_style_default_text5);
        DefaultText6 = findViewById(R.id.panel_style_default_text6);
        ChangeBackground = findViewById(R.id.panel_style_default_text7);
        view_line5 = findViewById(R.id.panel_style_view5);
    }

    @Override
    public void getSystemBattery() {
        BatteryManager bm = (BatteryManager) getSystemService(Context.BATTERY_SERVICE);
        int level = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        battery.setProgress(level);
        String battery = level + "%";
        battery_value_tv.setText(battery);
    }

    @Override
    public void setData(WeatherNowAdapter.NowBean now) {
        runOnUiThread(() -> {
            CityName.setText(sets.getDefaultCityName());
            Tem.setText(String.format("%s℃", now.getTemp()));
            Weather_Text.setText(now.getText());
            Weather_Icon.setImageBitmap(AppToolUtil.getweatherIcon(PanelModeView.this, now.getIcon()));
            Wet.setText(String.format("湿度%s%%", now.getHumidity()));
            WindSpeed.setText(now.getWindDir());
            Date.setText(AppToolUtil.getSimpleDate("yyyy年MM月dd日"));
            Update.setText(String.format("云量%s", now.getCloud()));
            Week.setText(AppToolUtil.getDayInWeek());
            vioce();
        });
    }

    @Override
    public void vioce() {
        final AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
        final int VoiceMode = AudioManager.STREAM_MUSIC;
        int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        ChangeVoice.setMax(max);
        int voice = am.getStreamVolume(VoiceMode);
        ChangeVoice.setProgress(voice);
        Voice_text.setText(String.valueOf(voice));
        ChangeVoice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar p1, int p2, boolean p3) {
                //振动
                am.setStreamVolume(AudioManager.STREAM_MUSIC, Math.max(p2, 0), AudioManager.FLAG_PLAY_SOUND);
                Voice_text.setText(String.valueOf(p2));
            }

            @Override
            public void onStartTrackingTouch(SeekBar p1) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar p1) {
            }

        });
    }

    @Override
    public void exit() {
        if (tasks.size() > 0) {
            final MDialog dialog = new MDialog(PanelModeView.this);
            dialog.setTitle("提示");
            dialog.setCancelable(false);
            dialog.setMessage("是否保存任务？");
            dialog.setPositiveButton("确定", () -> {
                Gson json = new Gson();
                String tasks2 = json.toJson(tasks);
                sets.setTaskCache(tasks2);
                finish();
            });
            dialog.setNegativeBotton("取消", () -> {
                sets.setTaskCache("");
                finish();
            });
            dialog.show();
        } else {
            finish();
        }
    }

    private void autoSave() {
        Timer timer = new Timer();
        TimerTask timerTask_save = new TimerTask() {
            @Override
            public void run() {
                if (tasks.size() > 0) {
                    Gson json = new Gson();
                    String tasks2 = json.toJson(tasks);
                    sets.setTaskCache(tasks2);
                }
            }
        };
        timer.schedule(timerTask_save, 0, 60000);
    }

    private void toast(String str) {
        runOnUiThread(() -> MToast.show(PanelModeView.this, str));
    }

    @Override
    public void update() {
        if (System.currentTimeMillis() - updateTime < 60000) {
            toast("请一分钟后再试");
        } else {
            IAppWeatherHelper helper = AppWeatherManager.getHelper();
            helper.getWeatherNow(sets.getDefaultCityCode(), new IAppWeatherHelper.NowWeatherResponse() {
                @Override
                public void success(WeatherNowAdapter data) {
                    toast("更新数据成功");
                    setData(data.getNowBean());
                    updateTime = System.currentTimeMillis();
                }

                @Override
                public void fail(String err) {

                }
            });
        }
    }

    @Override
    public void setStyle(boolean isUseBlackStyle, int TextSize) {
        int color;
        int textColor;
        if (isUseBlackStyle) {
            color = Color.BLACK;
            textColor = Color.WHITE;
        } else {
            color = Color.WHITE;
            textColor = Color.BLACK;
        }
        getWindow().setStatusBarColor(color);
        if (!new File(AppToolUtil.getPanelModeBackgroundPic(this)).exists()) {
            Background.setBackgroundColor(color);
        } else {
            Background.setBackground(new BitmapDrawable(BitmapFactory.decodeFile(AppToolUtil.getPanelModeBackgroundPic(this))));
        }
        Clock.setTextColor(textColor);
        Clock.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Pixel.ttf"));
        CityName.setTextColor(textColor);
        CityName.setTextSize(TextSize);
        ChangeBackground.setTextColor(textColor);
        ChangeBackground.setTextSize(TextSize);
        Weather_Text.setTextColor(textColor);
        Weather_Text.setTextSize(TextSize);
        Tem.setTextColor(textColor);
        Tem.setTextSize(TextSize);
        Wet.setTextColor(textColor);
        Wet.setTextSize(TextSize);
        view_line.setBackgroundColor(textColor);
        view_line2.setBackgroundColor(textColor);
        WindSpeed.setTextColor(textColor);
        WindSpeed.setTextSize(TextSize);
        Update.setTextColor(textColor);
        Update.setTextSize(TextSize);
        DefaultText.setTextColor(textColor);
        DefaultText.setTextSize(TextSize);
        Voice_text.setTextColor(textColor);
        Voice_text.setTextSize(TextSize);
        Week.setTextColor(textColor);
        Week.setTextSize(TextSize);
        Date.setTextColor(textColor);
        Date.setTextSize(TextSize);
        DefaultText2.setTextColor(textColor);
        DefaultText2.setTextSize(TextSize);
        DefaultText3.setTextColor(textColor);
        DefaultText3.setTextSize(TextSize);
        DefaultText4.setTextColor(textColor);
        DefaultText4.setTextSize(TextSize);
        view_line3.setBackgroundColor(textColor);
        DefaultText5.setTextColor(textColor);
        DefaultText5.setTextSize(13);
        DefaultText6.setTextColor(textColor);
        DefaultText6.setTextSize(TextSize);
        view_line4.setBackgroundColor(textColor);
        battery_value_tv.setTextColor(textColor);
        battery_name_tv.setTextColor(textColor);
        view_line5.setBackgroundColor(textColor);
    }

    @Override
    public void startTimerTask() {
        time = new Timer();
        //一小时
        long halfHour = 3600000;
        time.schedule(timertask, 0, halfHour);
    }

    private void selectBitmap(int type) {
        if (ActivityCompat.checkSelfPermission(PanelModeView.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, type);
        } else {
            ActivityCompat.requestPermissions(PanelModeView.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            toast("没有储存权限");
        }
    }

    @Override
    public void upDateTasks(boolean isUseBlackStyle) {
        Tasks.removeAllViews();
        int color;
        int textColor;
        if (isUseBlackStyle) {
            color = Color.BLACK;
            textColor = Color.WHITE;
        } else {
            color = Color.WHITE;
            textColor = Color.BLACK;
        }
        if (tasks.size() != 0) {
            for (final PanelTaskUtil data : tasks) {
                Tasks.setGravity(Gravity.START);
                @SuppressLint("InflateParams") final View view = LayoutInflater.from(PanelModeView.this).inflate(R.layout.panel_task_line, null);
                View line1 = view.findViewById(R.id.panel_task_view);
                line1.setBackgroundColor(textColor);
                View line2 = view.findViewById(R.id.panel_task_view2);
                line2.setBackgroundColor(textColor);
                LinearLayout bg = view.findViewById(R.id.panel_task_bg);
                bg.setBackgroundColor(color);
                @SuppressLint("CutPasteId") MTextView text = view.findViewById(R.id.panel_task_text);
                if (!data.getIsFinished()) {
                    text.setText(data.getTaskName());
                } else {
                    SpannableString str = new SpannableString(data.getTaskName());
                    StrikethroughSpan ss = new StrikethroughSpan();
                    str.setSpan(ss, 0, str.length(), SpannableString.SPAN_INCLUSIVE_INCLUSIVE);
                    text.setText(str);
                }
                text.setTextSize(13);
                text.setTextColor(textColor);
                CheckBox check = view.findViewById(R.id.panel_task_check_box);
                check.setChecked(data.getIsFinished());
                check.setOnCheckedChangeListener((p1, p2) -> {
                    Tasks.removeView(view);
                    data.setIsFinished(p2);
                    @SuppressLint("CutPasteId") MTextView text1 = view.findViewById(R.id.panel_task_text);
                    if (!data.getIsFinished()) {
                        text1.setText(data.getTaskName());
                    } else {
                        SpannableString str = new SpannableString(data.getTaskName());
                        StrikethroughSpan ss = new StrikethroughSpan();
                        str.setSpan(ss, 0, str.length(), SpannableString.SPAN_INCLUSIVE_INCLUSIVE);
                        text1.setText(str);
                    }
                    Tasks.addView(view);
                    tasks.remove(data);
                    tasks.add(data);
                });
                bg.setOnLongClickListener(p1 -> {
                    tasks.remove(data);
                    Tasks.removeView(view);
                    upDateTasks(sets.getPanelTheme());
                    toast("删除任务");
                    return false;
                });
                Tasks.addView(view);
            }
        } else {
            Tasks.removeAllViews();
            Tasks.setGravity(Gravity.CENTER);
            MTextView t1 = new MTextView(PanelModeView.this);
            t1.setText("没有添加任务");
            t1.setTextSize(13);
            t1.setTextColor(textColor);
            Tasks.addView(t1);
        }
    }

    @Override
    public void checkCache() {
        final String data = sets.getTaskCache();
        if (data != null && !data.equals("")) {
            //有缓存数据
            final MDialog dialog = new MDialog(PanelModeView.this);
            dialog.setTitle("提示");
            dialog.setCancelable(false);
            dialog.setMessage("检测到本地有任务缓存，是否立即恢复？");
            dialog.setPositiveButton("确定", () -> {
                Gson gson = new Gson();
                Type listtype = new TypeToken<List<PanelTaskUtil>>() {
                }.getType();
                tasks = gson.fromJson(data, listtype);
                upDateTasks(sets.getPanelTheme());
                sets.setTaskCache("");
            });
            dialog.setNegativeBotton("取消", () -> {
                upDateTasks(sets.getPanelTheme());
                sets.setTaskCache("");
            });
            dialog.show();
        }
        upDateTasks(sets.getPanelTheme());
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(listener);
        time.cancel();
        timertask.cancel();
        super.onDestroy();
    }

    TimerTask timertask = new TimerTask() {
        @Override
        public void run() {
            update();
        }
    };

    public void exit(View view) {
        exit();
    }

    public void updateData(View view) {
        update();
    }

    public void changetheme(View view) {
        if (sets != null) {
            boolean a = !sets.getPanelTheme();
            setStyle(a, 13);
            sets.setPanelTheme(a);
            upDateTasks(a);
        }
    }

    public static final int _REQUEST_ADD_DATA = 1001;

    public void addTask(View view) {
        Intent intent = new Intent(this, PannelAddTaskActivity.class);
        startActivityForResult(intent, _REQUEST_ADD_DATA);
    }

    public void changebackground(View view) {
        MDialog mDialog = new MDialog(this);
        mDialog.setTitle("提示");
        mDialog.setMessage("请选择操作");
        mDialog.setPositiveButton("选取背景", () -> {
            selectBitmap(_REQUEST_GET_PIC);
        });
        mDialog.setNegativeBotton("恢复默认", () -> {
            new File(AppToolUtil.getPanelModeBackgroundPic(this)).delete();
            if (sets != null) {
                boolean a = sets.getPanelTheme();
                setStyle(a, 13);
            }
        });
        mDialog.setNavigateBotton("取消", null);
        mDialog.show();
    }


    class MyBatteryListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context p1, Intent p2) {
            if (p2.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                getSystemBattery();
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0) {
            toast("获取权限成功");
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == _REQUEST_GET_PIC && resultCode == RESULT_OK) {
            UCrop.of(data.getData(), Uri.fromFile(new File(AppToolUtil.getPanelModeBackgroundPic(PanelModeView.this)))).withAspectRatio(600, 300).start(PanelModeView.this);
            setStyle(sets.getPanelTheme(), 13);
        } else if (requestCode == _REQUEST_ADD_DATA && resultCode == RESULT_OK) {
            String[] tasks_str = data.getStringArrayExtra("tasks");
            if (tasks_str != null) {
                for (String str : tasks_str) {
                    PanelTaskUtil pt = new PanelTaskUtil();
                    pt.setTaskName(str);
                    pt.setIsFinished(false);
                    tasks.add(pt);
                }
            }
            upDateTasks(sets.getPanelTheme());
        }
    }

    boolean IsExit = false;
    ExitHandle exit = new ExitHandle();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!IsExit) {
                toast("再按一次退出");
                IsExit = true;
                exit.sendEmptyMessageDelayed(0, 2000);
                return false;
            } else {
                exit();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("HandlerLeak")
    class ExitHandle extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            IsExit = false;
            super.handleMessage(msg);
        }
    }

}